const express = require('express')
const app = express();
const path = require('path')

// 处理请求中间件
app.use(express.urlencoded())
app.use(express.json())


app.get("/user", (req, res) => {
    // console.log(req.query);
    const {
      userId
    } = req.query;
  
    //如果查询失败
    if (userId !== "001") {
      return res.send({
        code: 10001,
        msg: "查询失败",
        data: null
      })
    }
    //查询成功 响应
    res.send({
      code: 10000,
      msg: "查询成功",
      data: {
        name: "xiaoA",
        age: 18,
        sex: "男"
      }
    })
  
  })

//设置一个延迟请求的测试，来测试取消请求
app.get("/userTime", (req, res) => {
  setTimeout(()=>{
// console.log(req.query);
const {
  userId
} = req.query;

//如果查询失败
if (userId !== "001") {
  return res.send({
    code: 10001,
    msg: "查询失败",
    data: null
  })
}
//查询成功 响应
res.send({
  code: 10000,
  msg: "查询成功",
  data: {
    name: "xiaoA",
    age: 18,
    sex: "男"
  }
})
  },3000)

})

//加载静态资源
app.get('/1',(req,res)=>{
    const filePath = path.resolve(__dirname,'./01-请求拦截器.html')

    res.sendFile(filePath)
})

app.get('/2',(req,res)=>{
  const filePath = path.resolve(__dirname,'./02.响应拦截器.html')

  res.sendFile(filePath)
})  


app.get('/3',(req,res)=>{
  const filePath = path.resolve(__dirname,'./拦截器练习.html')

  res.sendFile(filePath)
})

app.get('/4',(req,res)=>{
  const filePath = path.resolve(__dirname,'./拦截器取消请求.html')

  res.sendFile(filePath)
})  



app.listen('3030',()=>{
    console.log(
        '启动成功 地址：http://127.0.0.1:3030  ');
})